import React, { useEffect, useMemo } from 'react';
import { useCurrentComponent } from '../../../hooks/useCurrentComponent';
import { ComponentNode } from '../../../store';

const ComponentPreview: React.FC = () => {
  const { components, componentConfig } = useCurrentComponent();

  /**
   * @description 渲染组件
   */
  const renderComponent = useMemo(() => {
    const recursionRender = (list: ComponentNode[]): React.ReactNode[] => {
      return list.map((component) => {
        const config = componentConfig[component.name];
        if (!config?.prod) {
          console.error(`组件 ${component.name} 未配置`);
          return null;
        }

        // 处理事件绑定
        const eventHandlers = component.bindEvents?.reduce((acc, event) => {
          // 从事件描述中提取事件名（例如 onClick）
          const eventName = event.desc.split(" ")[0] as keyof React.DOMAttributes<HTMLElement>;
          
          try {
            // 使用闭包包装函数代码
            const handler = new Function(`return ${event.code}`)();
            acc[eventName] = handler;
          } catch (error) {
            console.error(`事件处理函数解析失败 (${eventName}):`, error);
          }
          return acc;
        }, {} as Record<string, React.EventHandler<any>>);

        return React.createElement(
          config.prod,
          {
            className: `
              group relative
              min-h-[40px] min-w-[80px]
              rounded-lg border-2 border-solid border-transparent
              p-4 transition-all
              hover:border-blue-200 hover:bg-blue-50/50
              m-2
              ${component.children?.length ? "space-y-4" : ""}
            `,
            style: {
              boxShadow: "0 2px 8px -2px rgba(0, 0, 0, 0.05)",
            },
            key: component.id,
            id: component.id,
            name: component.name,
            ...config.defaultProps,    // 组件默认 props
            ...component.props,        // 用户自定义 props
            ...eventHandlers,          // 事件处理函数
            children: component.children?.length
              ? recursionRender(component.children)
              : null,
          }
        );
      });
    };

    return components && recursionRender(components);
  }, [components, componentConfig]);

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 p-8 w-full">
      <div className="relative z-10 space-y-6">
        {renderComponent || (
          // 空状态提示
          <div className="flex h-96 items-center justify-center rounded-xl border-2 border-dashed border-gray-200 bg-white text-gray-400">
            <span className="animate-pulse">从左侧拖拽组件开始设计</span>
          </div>
        )}
      </div>
    </div>
  );
};

export default ComponentPreview;